﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using AdvCMS.Data;
using AdvCMS.Data.Repositories;
using AdvCMS.Factory;
using AdvCMS.Models;

namespace AdvCMS.Controllers
{
    public class InstallController : Controller
    {
        private IUserRepository userRepository;
        
        protected override void Initialize(RequestContext requestContext)
        {
            Factory.RepositoryFactory factory = new RepositoryFactory();
            userRepository = factory.NewUserRepository();
            base.Initialize(requestContext);
        }
        //
        // GET: /Install/
        public ViewResult Index()
        {
            return View();
        }
        // 
        [HttpPost]
        public ActionResult Index(ServerModel serverModel)
        {
            #region ModelState Valid
            if (ModelState.IsValid)
            {
                // Add key in web.config
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
                string connectStr = String.Format("data source={0};Initial Catalog={1};uid={2};password={3};Integrated Security=SSPI",serverModel.ServerName,serverModel.DatabaseName,serverModel.UserName,serverModel.UserPassword);
                
                if (section != null)    
                {
                    if (section.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"] == null)
                    {
                         ConnectionStringSettings setting = new ConnectionStringSettings();
                         setting.Name = "AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString";
                         section.ConnectionStrings.Add(setting);
                    }
                    section.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"].ConnectionString = connectStr;
                    section.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"].ProviderName = "System.Data.SqlClient";
                    config.Save();
                }
                return RedirectToAction("SetupTables");
            }
            #endregion
                   
            else {

                // Validation error - redisplay form
                return View();
            }

        }

        [HttpPost]
        public ActionResult SetupTables(UserModel userModel)
        {
            if (ModelState.IsValid)
            {
                IAdvUser user = userRepository.Create();
                user.Username = userModel.UserName;
                user.Password = userModel.UserPassword;
                user.Email = userModel.Email;
                userRepository.Insert(user);
                userRepository.Update();
                return RedirectToAction("Cleanup", new { id = user.Id });
            }
            return View();
        }

        public ActionResult SetupTables()
        {
            string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AdvCMS.Data.Linq.Properties.Settings.AdvCMSConnectionString"].ConnectionString;
            SqlConnection SqlConn = new SqlConnection(connStr);
         
            try
            {
                // Open Connection
                SqlConn.Open();
                // Read /App_data/tables into a string
              
               FileInfo file = new FileInfo(Server.MapPath("~/App_Data/tables.sql"));
                string script = file.OpenText().ReadToEnd();
              
                // Form SQL Command
                SqlCommand cmd = new SqlCommand(script,SqlConn);
                // Command.Execute SQL String
                cmd.ExecuteNonQuery();
               
            }
            finally
            {
                if (SqlConn != null)
                {
                    SqlConn.Close();
                }
            }
            return View();
        }


       
        public ActionResult Cleanup(int id)
        {
            IAdvUser user = userRepository.Get(id);
            UserModel model =new UserModel();
            if (user != null)
            {
                model.UserName = user.Username;
                model.UserPassword = user.Password;
                model.Email = user.Email;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Cleanup()
        {
            if (ModelState.IsValid)
            {
                string[] filepaths = Directory.GetFiles(Server.MapPath("~/Views/Install"));
                foreach (string filePath in filepaths)
                {
                    System.IO.File.Delete(filePath);
                  
                }
            }
            return RedirectToAction("Completed","Home");
            
        }
    }
}


